<template>
  <div class="login-container">
    <div class="login-card">
      <el-tabs v-model="activeTab" class="login-tabs" stretch>

        <el-tab-pane label="登录" name="login">
          <div class="login-header">
            <h1 class="login-title">登录</h1>
          </div>
          <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" @keyup.enter="handleLogin">
            <el-form-item prop="username">
              <el-input v-model="loginForm.username" placeholder="用户名" size="large" class="login-input" />
            </el-form-item>

            <el-form-item prop="password">
              <el-input v-model="loginForm.password" type="password" show-password placeholder="密码" size="large"
                class="login-input" />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" size="large" @click="handleLogin" :loading="loading" class="login-button">
                {{ loading ? '登录中' : '登录' }}
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="注册" name="register">
          <div class="login-header">
            <h1 class="login-title">注册</h1>
          </div>
          <el-form ref="registerFormRef" :model="registerForm" :rules="registerRules" @keyup.enter="handleRegister">
            <el-form-item prop="username">
              <el-input v-model="registerForm.username" placeholder="设置用户名" size="large" class="login-input" />
            </el-form-item>

            <el-form-item prop="password">
              <el-input v-model="registerForm.password" type="password" show-password placeholder="设置密码" size="large"
                class="login-input" />
            </el-form-item>

            <el-form-item prop="confirmPassword">
              <el-input v-model="registerForm.confirmPassword" type="password" show-password placeholder="确认密码"
                size="large" class="login-input" />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" size="large" @click="handleRegister" :loading="registerLoading"
                class="login-button">
                {{ registerLoading ? '注册中' : '立即注册' }}
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

      </el-tabs>

      <div class="login-tips" v-if="activeTab === 'login'">
        <p class="tip-text">测试账号：admin / 123</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { loginApi, registerApi } from '@/api/user'
import type { RegisterRequest } from '@/types/user.d' // 确保导入 RegisterRequest

// 路由和状态管理
const router = useRouter()
const userStore = useUserStore()
const activeTab = ref('login')

// ==================== 登录部分 ====================
const loginFormRef = ref<FormInstance>()
const loading = ref(false)
const loginForm = reactive({
  username: '',
  password: ''
})

const loginRules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度为 3-20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少 6 个字符', trigger: 'blur' }
  ]
})

// 登录处理
const handleLogin = async () => {
  if (!loginFormRef.value) return

  await loginFormRef.value.validate(async (valid) => {
    if (!valid) return

    loading.value = true
    try {
      const response = await loginApi({
        username: loginForm.username,
        password: loginForm.password
      })

      userStore.setToken(response.data as string)

      ElMessage.success(response.message || '登录成功')

      await new Promise(resolve => setTimeout(resolve, 50));

      await router.replace('/')
      console.log(response.data);
      localStorage.setItem('token', response.data as string);
      console.log('123token', localStorage.getItem('token'));
    } catch (error: any) {
      // 优化错误信息提取
      const errorMessage = error?.response?.data?.message || error?.message || '登录失败'
      ElMessage.error(errorMessage)
    } finally {
      loading.value = false
    }
  })
}

// ==================== 注册部分 ====================
const registerFormRef = ref<FormInstance>()
const registerLoading = ref(false)
const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  phone: '',
  email: '',
  realName: '',
  role: 'admin',// 默认角色为 'user'
  avatar: '',
})

// 确认密码验证
const validateConfirmPassword = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== registerForm.password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const registerRules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度为 3-20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少 6 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
})

// 注册处理
const handleRegister = async () => {
  if (!registerFormRef.value) return

  await registerFormRef.value.validate(async (valid) => {
    if (!valid) return

    registerLoading.value = true
    try {

      const paramsToSend: RegisterRequest = {
        username: registerForm.username,
        password: registerForm.password,
        phone: registerForm.phone,
        email: registerForm.email,
        realname: registerForm.realName,
        role: registerForm.role,
        avatar: registerForm.avatar,
      }

      const response = await registerApi(paramsToSend) // 使用包含 phone 的参数进行调用

      ElMessage.success(response.message || '注册成功！请登录')
      registerFormRef.value?.resetFields()
      activeTab.value = 'login'
    } catch (error: any) {
      // 优化错误信息提取
      const errorMessage = error?.response?.data?.message || error?.message || '注册失败'
      ElMessage.error(errorMessage)
    } finally {
      registerLoading.value = false
    }
  })
}
</script>

<style scoped>
.login-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f5f5f5;
}

.login-card {
  width: 400px;
  padding: 48px 40px;
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.login-tabs {
  margin: 0 -10px;
}

:deep(.el-tabs__header) {
  margin-bottom: 25px;
}

:deep(.el-tabs__nav-wrap::after) {
  display: none;
}

:deep(.el-tabs__item) {
  font-size: 16px;
  font-weight: 500;
  padding: 0 20px;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-title {
  font-size: 28px;
  color: #303133;
  margin: 0;
  font-weight: 600;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-form-item:last-child) {
  margin-bottom: 0;
}

:deep(.el-form-item__error) {
  font-size: 12px;
  color: #f56c6c;
  margin-top: 4px;
}

.login-input :deep(.el-input__wrapper) {
  background: #ffffff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  box-shadow: none;
  height: 48px;
  padding: 0 16px;
  transition: border-color 0.2s ease;
}

.login-input :deep(.el-input__wrapper:hover) {
  border-color: #409eff;
}

.login-input :deep(.el-input__wrapper.is-focus) {
  border-color: #409eff;
  box-shadow: none;
}

.login-input :deep(.el-input__inner) {
  font-size: 14px;
  color: #303133;
}

.login-input :deep(.el-input__inner::placeholder) {
  color: #c0c4cc;
}

.login-button {
  width: 100%;
  height: 48px;
  background: #409eff;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.2s ease;
}

.login-button:hover {
  background: #66b1ff;
}

.login-button:active {
  background: #3a8ee6;
}

:deep(.el-button--primary.is-loading) {
  background: #79bbff;
}

.login-tips {
  text-align: center;
  margin-top: 24px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.tip-text {
  font-size: 13px;
  color: #909399;
  margin: 0;
  line-height: 1.6;
}
</style>
